package client

import (
	"chatting/client/image"
	"chatting/dao"
	"fmt"
	"fyne.io/fyne/v2"
	"fyne.io/fyne/v2/canvas"
	"fyne.io/fyne/v2/container"
	"fyne.io/fyne/v2/dialog"
	"fyne.io/fyne/v2/theme"
	"fyne.io/fyne/v2/widget"
)

func (la *LocalApp) BuildMainWindow() fyne.Window {
	window := la.app.NewWindow(localUser.Username)

	FriendList := widget.NewList(
		func() int {
			return len(localUser.User.Friends)
		},
		func() fyne.CanvasObject {
			image := &canvas.Image{}
			image.FillMode = canvas.ImageFillStretch
			label := widget.NewLabel("Test")
			labelHeight := label.MinSize().Height
			image.SetMinSize(fyne.NewSize(labelHeight, labelHeight))
			return container.NewBorder(nil, nil, image, nil, label)
		},
		func(id widget.ListItemID, object fyne.CanvasObject) {
			img := object.(*fyne.Container).Objects[1].(*canvas.Image)
			text := object.(*fyne.Container).Objects[0].(*widget.Label)
			headImage := image.GetHeadImage(localUser.Friends[id].Username)
			resource, err := fyne.LoadResourceFromPath(headImage)
			if err != nil {
				panic(err)
			}
			img.Resource = resource
			img.Refresh()
			text.SetText(localUser.Friends[id].Username)
		},
	)

	FriendList.OnSelected = func(id widget.ListItemID) {
		chatWindow := la.BuildChatWindow(localUser.Friends[id].Username)
		chatWindow.Show()
	}

	FriendNameEnter := widget.NewEntry()
	AddFriendForm := widget.NewForm(
		widget.NewFormItem("好友名", FriendNameEnter),
	)
	AddFriendForm.SubmitText = "提交"
	AddFriendForm.OnSubmit = func() {
		for _, friend := range localUser.Friends {
			if friend.Username == FriendNameEnter.Text {
				dialog.ShowInformation("添加好友错误", "目标已经是你的好友了", window)
				return
			}
		}
		user1 := dao.GetUserFromName(localUser.Username)
		user3 := dao.GetUserFromName(FriendNameEnter.Text)
		//fmt.Println("user3 is", user3)
		if user1.ID == 0 || user3.ID == 0 || user3.Username == localUser.Username {
			fmt.Println("是否dialog")
			dialog.ShowInformation("添加好友错误", "目标好友用户名可能错误", window)
			fmt.Println("是否dialog over")
			return
		}

		err := dao.AddFriend(user1, user3)
		if err != nil {
			fmt.Println(err)
			dialog.ShowInformation("添加好友错误", "目标好友用户名可能错误", window)
			return
		}
		dialog.ShowInformation("成功", "添加好友成功", window)
		FriendList.Refresh()
		return
	}

	under := container.NewMax()

	friendListbuttom := widget.NewButtonWithIcon("好友", theme.HomeIcon(), func() {
		under.RemoveAll()
		under.Add(FriendList)
		FriendList.Refresh()
		under.Refresh()
	})

	addFriendButtom := widget.NewButtonWithIcon("添加好友", theme.ContentAddIcon(), func() {
		under.RemoveAll()
		under.Add(AddFriendForm)
		under.Refresh()
	})

	head := container.NewGridWithColumns(2, friendListbuttom, addFriendButtom)

	mainC := container.NewBorder(head, nil, nil, nil, under)

	window.SetContent(mainC)
	return window
}
